﻿
var common = {

    commonAjax: function (options) {

        common.loading(options.loadingCtrl);

        $.ajax({
            type: options.type,
            //contentType: 'application/json',
            url: options.url,
            data: options.data,
            //dataType: 'json',
            success: function (ctx) {

                common.loadComplete(options.loadingCtrl);

                if (common.checkValue(options.alert)) {
                    swal({
                        title: "",
                        text: "提交成功, 2秒后自动关闭。",
                        type: "success",
                        timer: 2000,
                        showConfirmButton: true
                    },
                    function () {
                        swal.close();
                        options.sMethod(ctx);
                    });

                    return;
                }

                options.sMethod(ctx);
            },
            error: function (ctx) {
                debugger;
                common.loadComplete(options.loadingCtrl);

                if (options.fMethod == undefined || options.fMethod == null || options.fMethod == "") {

                    if (common.checkValue(ctx.responseJSON.Message))
                        common.alertMessage(ctx.responseJSON.Message, ctx.status);
                    else
                        common.alertMessage("操作失败,请重新提交。", ctx.status);

                    return;
                }

                options.fMethod(ctx);
            }
        });
    },

    getUrlArgStr: function () {

        var url = decodeURI(location.search);
        var param = [];
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                param[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
            }
        }

        return param;
    },

    alertMessage: function (msg, status) {

        if (status == undefined)
            status = 0;

        switch (status) {
            //case 400:
            //    alert(data.Message);
            //    break;
            case 400:
                if (common.checkValue(msg))
                    swal({
                        text: msg,
                        title: '',
                        type: "warning",
                        html: true
                    });
                else
                    window.location = "../login.html";
                break;
            case 401:
                window.location = "../login.html";
                break;
            default:
                swal({
                    //text: "操作失败,请重新提交。",
                    text: msg,
                    title: '',
                    type: "warning",
                    html: true
                });
        }
    },

    loading: function (loadingCtrl) {
        if (common.checkValue(loadingCtrl)) {
            //loadingCtrl.append('<div class="message-loading-overlay"><img class="icon-spinner icon-spin" style="width: 212px"></img></div>')
            loadingCtrl.append('<div class="message-loading-overlay"><div class="loding-img" style="width: 212px"></div></div>')
        }
    },

    loadComplete: function (loadingCtrl) {
        if (common.checkValue(loadingCtrl)) {
            loadingCtrl.find('.message-loading-overlay').remove();
        }
    },

    GetSHA: function (val) {

        var shaObj = new jsSHA("SHA-512", "TEXT");
        shaObj.update(val);
        return shaObj.getHash("HEX");
    },

    encrypt: function (str, pwd) {
        if (pwd == null || pwd.length <= 0) {
            pwd = "bingo123";
        }

        var prand = "";
        for (var i = 0; i < pwd.length; i++) {
            prand += pwd.charCodeAt(i).toString();
        }
        var sPos = Math.floor(prand.length / 5);
        var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos * 2) + prand.charAt(sPos * 3) + prand.charAt(sPos * 4) + prand.charAt(sPos * 5));
        var incr = Math.ceil(pwd.length / 2);
        var modu = Math.pow(2, 31) - 1;
        if (mult < 2) {
            alert("Algorithm cannot find a suitable hash. Please choose a different password. \nPossible considerations are to choose a more complex or longer password.");
            return null;
        }
        var salt = Math.round(Math.random() * 1000000000) % 100000000;
        prand += salt;
        while (prand.length > 10) {
            prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString();
        }
        prand = (mult * prand + incr) % modu;
        var enc_chr = "";
        var enc_str = "";
        for (var i = 0; i < str.length; i++) {
            enc_chr = parseInt(str.charCodeAt(i) ^ Math.floor((prand / modu) * 255));
            if (enc_chr < 16) {
                enc_str += "0" + enc_chr.toString(16);
            } else enc_str += enc_chr.toString(16);
            prand = (mult * prand + incr) % modu;
        }
        salt = salt.toString(16);
        while (salt.length < 8) salt = "0" + salt;
        enc_str += salt;

        return enc_str;
    },

    decrypt: function (str, pwd) {
        if (str == null || str.length < 8) {
            alert("A salt value could not be extracted from the encrypted message because it's length is too short. The message cannot be decrypted.");
            return;
        }
        if (pwd == null || pwd.length <= 0) {
            pwd = "bingo123";
        }
        var prand = "";
        for (var i = 0; i < pwd.length; i++) {
            prand += pwd.charCodeAt(i).toString();
        }
        var sPos = Math.floor(prand.length / 5);
        var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos * 2) + prand.charAt(sPos * 3) + prand.charAt(sPos * 4) + prand.charAt(sPos * 5));
        var incr = Math.round(pwd.length / 2);
        var modu = Math.pow(2, 31) - 1;
        var salt = parseInt(str.substring(str.length - 8, str.length), 16);
        str = str.substring(0, str.length - 8);
        prand += salt;
        while (prand.length > 10) {
            prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString();
        }
        prand = (mult * prand + incr) % modu;
        var enc_chr = "";
        var enc_str = "";
        for (var i = 0; i < str.length; i += 2) {
            enc_chr = parseInt(parseInt(str.substring(i, i + 2), 16) ^ Math.floor((prand / modu) * 255));
            enc_str += String.fromCharCode(enc_chr);
            prand = (mult * prand + incr) % modu;
        }
        return enc_str;
    },

    GetCtrlValues: function (option) {
        var contentID = option.ContentID.toString().indexOf("#") > 0 ? option.ContentID : "#" + option.ContentID;
        var objParent = $(contentID);

        var resultData = {};
        objParent.find("input[type='text'],textarea").each(function () {
            var objThis = $(this);
            resultData[objThis.attr("id")] = objThis.val();
        })
        objParent.find("input[type='password']").each(function () {
            var objThis = $(this);
            var objVal = objThis.val();
            if (objVal != undefined || objVal != "")
                objVal = common.GetSHA(objVal)
            resultData[objThis.attr("id")] = objVal;
        })
        objParent.find("input[type='number']").each(function () {
            var objThis = $(this);
            resultData[objThis.attr("id")] = objThis.val();
        })
        objParent.find("select").each(function () {
            var objThis = $(this);
            resultData[objThis.attr("id")] = objThis.val();
        })
        objParent.find("input[type='radio']").each(function () {
            var objThis = $(this);
            if ($(this).attr("checked") || $(this).prop("checked"))
                resultData[objThis.attr("name")] = objThis.val();
        })
        objParent.find("input[type='checkbox']").each(function () {
            var objThis = $(this);
            if ($(this).attr("checked") || $(this).prop("checked")) {
                var TempArr = resultData[objThis.attr("name")];
                if (TempArr == undefined)
                    TempArr = "";

                TempArr += objThis.val() + "$%#";
                resultData[objThis.attr("name")] = TempArr;
            }

        })
        objParent.find("input[type='date']").each(function () {
            var objThis = $(this);
            resultData[objThis.attr("id")] = objThis.val();
        })
        objParent.find("a").each(function () {
            var objThis = $(this);
            if ($(this).attr("class") == "chosen" || $(this).prop("class") == "chosen")
                resultData[objThis.attr("name")] = objThis.attr("value");
        })

        if (option.returnJson == undefined || !option.returnJson)
            return resultData;
        else
            return JSON.stringify(resultData);

    },

    CacheObj: function (data, name) {

        var cacheArray = store.get(name);
        if (!common.checkValue(cacheArray))
            cacheArray = new Array();

        var obj = {};

        switch (name) {
            case "Project":
                var result = data.ResponseDict;
                obj.ProjectID = result.ProjectID;
                obj.ProjectName = result.ProjectName;
                obj.Address = result.Address;
                obj.CreateDate = result.CreateDate;
                obj.Amount = result.Amount;
                obj.StartDate = result.StartDate;
                obj.EndDate = result.EndDate;
                break;
        }

        for (var i = 0; i < cacheArray.length; i++) {
            if (obj.ProjectID == cacheArray[i].ProjectID)
                return;
        }

        if (cacheArray.length < 5) {
            cacheArray.push(obj);
        }
        else {
            cacheArray.splice(0, 1);
            cacheArray.push(obj);
        }

        store.set(name, cacheArray);

    },

    ListCacheObj: function (objName) {
        var cacheArray = store.get(objName);
        if (!common.checkValue(cacheArray) || cacheArray.length == 0)
            return;
        return cacheArray.reverse();
    },

    CreateController: function (option) {

        var app = common.checkValue(option.app) ? option.app : angular.module('myApp', []);

        app.controller(option.name, function ($http, $scope) {

            if (!common.checkValue(option.url)) {

                $scope.update = function (data) {

                    $scope.names = data;
                    $scope.$apply();
                }
            }
            else {
                $http.get(option.url).success(function (data) {

                    switch (option.objType) {
                        case "object":
                            $scope.names = data.ResponseObj;
                            break;
                        case "list":
                            $scope.names = data.ResponseList;
                            break;
                        case "dict":
                            $scope.names = data.ResponseDict;
                            break;
                        case "string":
                            $scope.names = data.ResponseStr;
                            break;
                    }

                    if (common.checkValue(option.cacheName))
                        common.CacheObj(data, option.cacheName);

                }).error(function (data, status, headers, config) {
                    common.alertMessage(data.Message, status);
                });
            }
        });
    },

    CreatePagingCtrl: function (option) {

        var app = common.checkValue(option.app) ? option.app : angular.module('myApp', ['ng-pagination']);
        var limit = 10;

        if (common.checkValue(option.limit))
            limit = option.limit;

        if (!common.checkValue(option.pars)) {
            option.pars = {};
        }

        option.pars.Start = 1;
        option.pars.Limit = limit;

        app.controller(option.name, function ($http, $scope) {

            if (!common.checkValue(option.url)) {

                $scope.update = function (data) {

                    $scope.names = data.ResponseList;
                    $scope.count = data.Count;

                    var total = Math.floor(data.Count / limit);

                    if (data.Count % limit > 0)
                        total++;

                    $scope.pageCount = total;

                    $scope.$apply();
                }

                $scope.onPageChange = function () {
                    option.pageChanged($scope);
                };
            }
            else {
                $http.post(option.url, option.pars).success(function (data) {

                    $scope.names = data.ResponseList;

                    var total = Math.floor(data.Count / limit);

                    if (data.Count % limit > 0)
                        total++;

                    $scope.pageCount = total;

                }).error(function (data, status, headers, config) {
                    common.alertMessage(data.Message, status);
                });

                $scope.onPageChange = function () {

                    option.pars.Start = $scope.currentPage;

                    $http.post(option.url, option.pars).success(function (data) {
                        $scope.names = data.ResponseList;
                    }).error(function (data, status, headers, config) {
                        common.alertMessage(data.Message, status);
                    });

                };
            }
        });
    },

    CreatePullDownCtrl: function (option) {

        var app = common.checkValue(option.app) ? option.app : angular.module('myApp', []);

        app.directive(option.dictName, function () {

            var p = 0, t = 0;

            return function (scope, elm, attr) {

                $(window).scroll(function () {

                    if (startLoad) {

                        //检查是上滚还是下滚，上滚的话就不加载数据
                        p = $(window).scrollTop();
                        if (t > p) {
                            t = p;
                            return;
                        }
                        else {
                            t = p;
                        }

                        //如果滚动条距离底部距离大于整个页面长度的90%，则加载数据
                        var pageYOffset = $(window)[0].pageYOffset;
                        var clientHeight = $(document)[0].documentElement.clientHeight;
                        var offsetHeight = $(document)[0].body.offsetHeight;

                        if (pageYOffset + clientHeight > offsetHeight * 0.9) {
                            scope.$apply(attr.whenScrolled);
                        }
                    }
                });
            };
        });

        app.controller(option.name, function ($http, $scope) {

            $scope.currentPage = 0;

            $scope.totalPages = 1;

            $scope.amount = 0;

            $scope.busy = false;

            $scope.names = [];

            //option.limit = common.checkValue(option.limit) ? option.limit : 10;

            $scope.loadMore = function () {

                option.pars.start = $scope.currentPage;

                if ($scope.currentPage < $scope.totalPages) {
                    
                    if ($scope.busy) {
                        return false;
                    }

                    $scope.busy = true;

                    //option.pars.limit = common.checkValue(option.limit) ? option.limit : 10;

                    //setTimeout(function () {
                    //$http.get(option.url + "?start=" + $scope.currentPage + "&limit=" + option.limit)
                    $http.post(option.url, option.pars)
                    .success(function (data) {

                        $scope.busy = false;

                        for (var i in data.ResponseList) {
                            $scope.names.push(data.ResponseList[i]);
                        }

                        var total = Math.floor(data.Count / option.pars.limit);

                        if (data.Count % option.pars.limit > 0)
                            total++;

                        $scope.totalPages = total;

                        $scope.amount = data.Count;

                        $scope.currentPage++;
                    });
                    //}, 5000);
                }
            }

            // 默认第一次加载数据
            $scope.loadMore();
        });
    },

    formatDescForDate: function (date) {
        if (date < '1990-01-01')
            return "-";

        return date;
    },

    validateForm: function (form, style) {

        var isValid = true;
        if (!common.checkValue(form) || !common.checkValue(style)) {
            form = $("#formValidate");
            style = $(".help-block");
        }

        form.validator("validate");
        style.each(function () {

            var val = $(this)[0].textContent;
            if (common.checkValue(val)) {
                isValid = false;
            }
        });

        return isValid;
    },

    checkValue: function (val) {
        if (val == "" || val == null || val == undefined)
            return false;

        return true;
    },

    ResetControls: function (parentControlID) {
        $('#' + parentControlID + '' + ' [clearafterclose=true]').each(function () {

            var obj = $(this);
            switch (obj[0].type) {
                case 'file':
                    obj.fileinput('clear');
                    break;
                case 'select-multiple':
                    obj.val("");
                    obj.trigger("chosen:updated");
                    break;
                default:
                    obj.val('');
                    break;
            }
        });
    }
}


